package com.onlinevideo.servlet;

import cn.hutool.json.JSONUtil;
import com.onlinevideo.data.ResultBean;
import com.onlinevideo.entity.*;
import com.onlinevideo.service.FavoritesService;
import com.onlinevideo.service.FavoritesVideoService;
import com.onlinevideo.service.VideoService;
import com.onlinevideo.service.impl.FavoritesServiceImpl;
import com.onlinevideo.service.impl.FavoritesVideoServiceImpl;
import com.onlinevideo.service.impl.VideoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class FavoritesServlet extends BaseServlet {
    private PrintWriter writer;
    FavoritesVideoService favoritesVideoService = new FavoritesVideoServiceImpl();
    FavoritesService favoritesService = new FavoritesServiceImpl();
    VideoService videoService = new VideoServiceImpl();

    protected void addCollection(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        writer = resp.getWriter();
        String favoritesIdStr = req.getParameter("favoritesId");

        Long favoritesId = Long.valueOf(favoritesIdStr);
        Long  videoId = Long.valueOf(req.getParameter("videoId"));
        FavoritesVideo favoritesVideo = new FavoritesVideo(null, favoritesId, videoId);
        List<FavoritesVideo> favoritesVideos = favoritesVideoService.queryByFavorAndVideo(favoritesId, videoId);
        //已收藏
        if (favoritesVideos != null && favoritesVideos.size() > 0) {
            int delete = favoritesVideoService.delete(favoritesVideos.get(0).getId());
            if (delete > 0) {
                Video video = videoService.queryById(videoId);
                long collectionCount = video.getCollectionCount() - 1;
                video.setCollectionCount(collectionCount);
                videoService.update(video);
                writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("已取消收藏")));
            } else {
                writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("取消收藏失败")));
            }
        } else {
            //未收藏
            int insert = favoritesVideoService.insert(favoritesVideo);
            if (insert > 0) {
                Video video = videoService.queryById(videoId);
                long collectionCount = video.getCollectionCount() + 1;
                video.setCollectionCount(collectionCount);
                videoService.update(video);
                writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("已收藏")));
            } else {
                writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("收藏失败")));
            }
        }

    }
    //根据收藏夹查询收藏视频
    protected void getCollectionItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            user = new User();
            user.setId(1L);
        }
        String favoritesIdStr = req.getParameter("collectionId");
        if (favoritesIdStr == null || !favoritesIdStr.matches("[0-9]+")) {
            return;
        }
        writer = resp.getWriter();
        Long favoritesId = Long.valueOf(favoritesIdStr);
        List<FavoritesVideo> favoritesVideos = favoritesVideoService.queryByFavorites(favoritesId);
        List<Video> videoList = new ArrayList<>();
        for (FavoritesVideo favoritesVideo : favoritesVideos) {
            Long videoId = favoritesVideo.getVideoId();
            Video video = videoService.queryById(videoId);
            if (video == null) {
                continue;
            }
            //借用video中的userId属性，暂存为收藏视频id
            video.setUserId(favoritesVideo.getId());
            //借用上传时间属性 存videoId
            video.setUploadTime(String.valueOf(video.getId()));
            videoList.add(video);
        }
        if (videoList.size() > 0) {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("获取收藏成功", videoList)));
        } else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("收藏夹为空")));
        }




    }

    //添加收藏夹
    protected void insert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      writer = resp.getWriter();
        HttpSession session = req.getSession();
        User user = (User)session.getAttribute("user");
        if(user == null){
            user = new User();
            user.setId(1L);
        }
        String favoritesName = req.getParameter("favoritesName");
        if(favoritesName==null || favoritesName.length()<=0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("新增失败，请输入收藏夹名称")));
            return ;
        }
        Long favoriteCount = favoritesService.queryByFavoriteCount(user.getId());
        if(favoriteCount>4L){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("新增失败，收藏夹数量只能小于5")));
            return ;
        }
        Favorites favorites = new Favorites(user.getId(), favoritesName);
        Favorites favorites1 = favoritesService.queryByFavoriteName(favorites);
        if(favorites1 != null ){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("新增失败，已经存在该收藏夹，请重新输入新的收藏夹名称")));
            return ;
        }
        int result = favoritesService.insert(favorites);
        if(result>0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("收藏夹添加成功")));
        }else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("收藏夹添加失败")));
        }
    }

    //修改收藏夹
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writer = resp.getWriter();
        HttpSession session = req.getSession();
        User user = (User)session.getAttribute("user");
        if(user == null){
            user = new User();
            user.setId(1L);
        }
        String favoritesName = req.getParameter("favoritesName");
        String favoritesId = req.getParameter("favoritesId");
        if(favoritesName==null || favoritesName.length()<=0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("修改失败，请输入收藏夹名称")));
            return ;
        }
        Favorites favorites = new Favorites(Long.valueOf(favoritesId),user.getId(), favoritesName);
        Favorites favorites1 = favoritesService.queryByFavoriteName(favorites);
        if(favorites1 != null ){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("修改失败，已经存在该收藏夹，请重新输入新的收藏夹名称")));
            return ;
        }
        int result = favoritesService.update(favorites);
        if(result>0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("收藏夹修改成功")));
        }else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("收藏夹修改失败")));
        }
    }

    //删除收藏夹
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writer = resp.getWriter();
        HttpSession session = req.getSession();
        User user = (User)session.getAttribute("user");
        if(user == null){
            user = new User();
            user.setId(1L);
        }
        String favoritesId = req.getParameter("favoritesId");
        int result = favoritesService.delete(Long.valueOf(favoritesId));
        if(result>0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("收藏夹删除成功")));
        }else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("收藏夹删除失败")));
        }
    }

    //取消收藏
    //删除收藏夹
    protected void unFavorites(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writer = resp.getWriter();
        HttpSession session = req.getSession();
        User user = (User)session.getAttribute("user");
        if(user == null){
            user = new User();
            user.setId(1L);
        }
        String favoritesId = req.getParameter("favoritesVideoId");
        int result = favoritesVideoService.delete(Long.valueOf(favoritesId));
        if(result>0){
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationSuccess("取消收藏成功")));
        }else {
            writer.write(JSONUtil.toJsonStr(ResultBean.scOperationError("取消收藏失败")));
        }
    }
}
